#!/usr/bin/env python3
"""
问题诊断脚本
详细检查环境和依赖，输出诊断报告
"""
import sys
import os
import subprocess
from pathlib import Path

def print_section(title):
    """打印章节标题"""
    print(f"\n{'='*50}")
    print(f" {title}")
    print('='*50)

def check_python():
    """检查Python环境"""
    print_section("Python环境检查")
    
    print(f"Python版本: {sys.version}")
    print(f"Python路径: {sys.executable}")
    print(f"Python版本信息: {sys.version_info}")
    
    if sys.version_info < (3, 8):
        print("❌ 警告: Python版本过低，建议使用3.8+")
        return False
    else:
        print("✅ Python版本符合要求")
        return True

def check_pip():
    """检查pip"""
    print_section("pip检查")
    
    try:
        result = subprocess.run([sys.executable, '-m', 'pip', '--version'], 
                              capture_output=True, text=True)
        print(f"pip版本: {result.stdout.strip()}")
        print("✅ pip可用")
        return True
    except Exception as e:
        print(f"❌ pip检查失败: {e}")
        return False

def check_packages():
    """检查Python包"""
    print_section("Python包检查")
    
    packages = [
        'fastapi', 'uvicorn', 'sqlalchemy', 'pydantic', 
        'python-jose', 'passlib', 'aiosqlite', 'structlog'
    ]
    
    installed = []
    missing = []
    
    for package in packages:
        try:
            # 特殊处理带横线的包名
            import_name = package.replace('-', '_')
            if package == 'python-jose':
                import_name = 'jose'
            
            __import__(import_name)
            print(f"✅ {package}")
            installed.append(package)
        except ImportError:
            print(f"❌ {package}")
            missing.append(package)
    
    print(f"\n已安装: {len(installed)}/{len(packages)} 个包")
    if missing:
        print(f"缺失包: {', '.join(missing)}")
        print(f"\n安装命令: pip install {' '.join(missing)}")
    
    return len(missing) == 0

def check_project_files():
    """检查项目文件"""
    print_section("项目文件检查")
    
    backend_dir = Path(__file__).parent
    
    files_to_check = [
        'main.py',
        'requirements.txt', 
        'app/__init__.py',
        'app/core/config.py',
        'app/core/database.py',
        'app/api/v1/router.py'
    ]
    
    all_exist = True
    for file_path in files_to_check:
        full_path = backend_dir / file_path
        if full_path.exists():
            print(f\"✅ {file_path}\")
        else:
            print(f\"❌ {file_path} (缺失)\")
            all_exist = False
    
    print(f\"\n项目根目录: {backend_dir}\")
    return all_exist

def test_import_main():
    \"\"\"测试导入主模块\"\"\"
    print_section(\"主模块导入测试\")
    
    try:
        # 添加当前目录到Python路径
        current_dir = Path(__file__).parent
        if str(current_dir) not in sys.path:
            sys.path.insert(0, str(current_dir))
        
        print(\"尝试导入main模块...\")
        import main
        print(\"✅ main模块导入成功\")
        
        print(\"尝试获取app实例...\")
        app = getattr(main, 'app', None)
        if app:
            print(\"✅ FastAPI app实例找到\")
            return True
        else:
            print(\"❌ 未找到FastAPI app实例\")
            return False
            
    except ImportError as e:
        print(f\"❌ main模块导入失败: {e}\")
        return False
    except Exception as e:
        print(f\"❌ 其他错误: {e}\")
        import traceback
        traceback.print_exc()
        return False

def check_environment_variables():
    \"\"\"检查环境变量\"\"\"
    print_section(\"环境变量检查\")
    
    important_vars = [
        'DATABASE_URL',
        'SECRET_KEY', 
        'ENVIRONMENT'
    ]
    
    for var in important_vars:
        value = os.environ.get(var)
        if value:
            if var == 'SECRET_KEY':
                print(f\"✅ {var}: ***隐藏***\")
            else:
                print(f\"✅ {var}: {value}\")
        else:
            print(f\"⚠️  {var}: 未设置\")

def create_test_database():
    \"\"\"创建测试数据库\"\"\"
    print_section(\"数据库连接测试\")
    
    try:
        os.environ[\"DATABASE_URL\"] = \"sqlite+aiosqlite:///./test_diagnostic.db\"
        print(f\"设置数据库URL: {os.environ['DATABASE_URL']}\")
        
        # 测试异步SQLite连接
        import asyncio
        import aiosqlite
        
        async def test_db():
            async with aiosqlite.connect('./test_diagnostic.db') as db:
                await db.execute('CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY)')
                await db.commit()
                print(\"✅ SQLite数据库连接成功\")
                
                # 清理测试文件
                try:
                    os.remove('./test_diagnostic.db')
                except:
                    pass
        
        asyncio.run(test_db())
        return True
        
    except Exception as e:
        print(f\"❌ 数据库连接失败: {e}\")
        return False

def main():
    \"\"\"主诊断函数\"\"\"
    print(\"SmartCity-LLM Trainer 环境诊断工具\")
    print(\"这个工具会检查您的环境是否可以运行项目\")
    
    results = []
    
    # 执行各项检查
    results.append((\"Python环境\", check_python()))
    results.append((\"pip工具\", check_pip()))
    results.append((\"Python包\", check_packages()))
    results.append((\"项目文件\", check_project_files()))
    results.append((\"主模块导入\", test_import_main()))
    results.append((\"数据库连接\", create_test_database()))
    
    # 检查环境变量（信息性检查）
    check_environment_variables()
    
    # 输出总结
    print_section(\"诊断总结\")
    
    passed = 0
    failed = 0
    
    for name, result in results:
        status = \"✅ 通过\" if result else \"❌ 失败\"
        print(f\"{name}: {status}\")
        if result:
            passed += 1
        else:
            failed += 1
    
    print(f\"\n总计: {passed} 项通过, {failed} 项失败\")
    
    if failed == 0:
        print(\"\n🎉 所有检查都通过了！您的环境应该可以正常运行项目。\")
        print(\"您可以尝试运行: python quick_start.py\")
    else:
        print(f\"\n⚠️  发现 {failed} 个问题，请根据上面的信息进行修复。\")
        
        if not any(result for name, result in results[:3]):  # Python, pip, packages
            print(\"\n建议操作:\")
            print(\"1. 确保安装了Python 3.8+\")
            print(\"2. 运行: pip install fastapi uvicorn sqlalchemy aiosqlite pydantic python-jose passlib\")
            print(\"3. 再次运行此诊断脚本\")

if __name__ == \"__main__\":
    try:
        main()
    except KeyboardInterrupt:
        print(\"\n\n诊断被用户中断\")
    except Exception as e:
        print(f\"\n\n诊断过程出现错误: {e}\")
        import traceback
        traceback.print_exc()
    finally:
        input(\"\n按回车键退出...\")